package com.housing.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.housing.domain.Attachment;
import com.housing.domain.HouseItem;
import com.housing.domain.bo.AttachmentBo;
import com.housing.domain.bo.HouseItemBo;
import com.housing.domain.vo.HouseItemVo;
import com.housing.domain.vo.RentalConfigVo;
import com.housing.enums.AttachmentSourceEnum;
import com.housing.enums.HousingTypeEnum;
import com.housing.mapper.AttachmentMapper;
import com.housing.mapper.HouseItemMapper;
import com.housing.mapper.RentalConfigMapper;
import com.zmetaport.common.core.utils.MapstructUtils;
import com.zmetaport.common.core.utils.StringUtils;
import com.zmetaport.common.mybatis.core.page.TableDataInfo;
import com.zmetaport.common.mybatis.core.page.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import com.housing.domain.bo.HouseBo;
import com.housing.domain.vo.HouseVo;
import com.housing.domain.House;
import com.housing.mapper.HouseMapper;
import com.housing.service.IHouseService;

import java.util.List;
import java.util.Map;
import java.util.Collection;
import java.util.stream.Collectors;

/**
 * 【请填写功能名称】Service业务层处理
 *
 * @author chensm
 * @date 2024-12-15
 */
@RequiredArgsConstructor
@Service
public class HouseServiceImpl implements IHouseService {

    private final HouseMapper baseMapper;

    private final AttachmentMapper attachmentMapper;
    private final HouseItemMapper houseItemMapper;
    private final RentalConfigMapper rentalConfigMapper;

    /**
     * 查询【请填写功能名称】
     */
    @Override
    public HouseVo queryById(Long id){
        HouseVo houseVo = baseMapper.selectVoById(id);
        houseVo.setAttachments(attachmentMapper.queryBySource(houseVo.getId(), AttachmentSourceEnum.HOUSE_ATTACH.getCode()));
        List<HouseItemVo> itemVos = houseItemMapper.queryBySource(houseVo.getId());
        for (HouseItemVo itemVo : itemVos) {
            itemVo.setAttachments(attachmentMapper.queryBySource(itemVo.getId(), AttachmentSourceEnum.ITEM_ATTACH.getCode()));
        }
        houseVo.setItems(itemVos);

        RentalConfigVo rentalConfigVo = rentalConfigMapper.queryBySource(id, HousingTypeEnum.HOUSE.getCode());
        BeanUtils.copyProperties(rentalConfigVo, houseVo);
        return houseVo;
    }

    /**
     * 查询【请填写功能名称】列表
     */
    @Override
    public TableDataInfo<HouseVo> queryPageList(HouseBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<House> lqw = buildQueryWrapper(bo);
        Page<HouseVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        if(CollUtil.isNotEmpty(result.getRecords())){
            List<Long> ids = result.getRecords().stream().filter(e -> e.getBuildingId() == 0).map(HouseVo::getId).collect(Collectors.toList());
            List<RentalConfigVo> rentalConfigVos = rentalConfigMapper.queryBySources(ids, HousingTypeEnum.HOUSE.getCode());
            result.getRecords().stream().filter(e -> e.getBuildingId() == 0).forEach(e -> {
                rentalConfigVos.stream().filter(rentalConfigVo -> rentalConfigVo.getSourceId().equals(e.getId())).findFirst().ifPresent(e1 -> {
                    BeanUtils.copyProperties(e1, e);
                });
            });

            List<Long> buildIds = result.getRecords().stream().filter(e -> e.getBuildingId() != 0).map(HouseVo::getId).collect(Collectors.toList());
            List<RentalConfigVo> rentalConfigVos2 = rentalConfigMapper.queryBySources(buildIds, HousingTypeEnum.BUILDING.getCode());
            result.getRecords().stream().filter(e -> e.getBuildingId() != 0).forEach(e -> {
                rentalConfigVos2.stream().filter(rentalConfigVo -> rentalConfigVo.getSourceId().equals(e.getId())).findFirst().ifPresent(e1 -> {
                    BeanUtils.copyProperties(e1, e);
                });
            });
        }
        return TableDataInfo.build(result);
    }

    /**
     * 查询【请填写功能名称】列表
     */
    @Override
    public List<HouseVo> queryList(HouseBo bo) {
        LambdaQueryWrapper<House> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<House> buildQueryWrapper(HouseBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<House> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getBuildingId() != null, House::getBuildingId, bo.getBuildingId());
        lqw.eq(bo.getOwnerId() != null, House::getOwnerId, bo.getOwnerId());
        lqw.eq(bo.getStatus() != null, House::getStatus, bo.getStatus());
        lqw.eq(StringUtils.isNotBlank(bo.getRoomNumber()), House::getRoomNumber, bo.getRoomNumber());
        lqw.eq(bo.getArea() != null, House::getArea, bo.getArea());
        lqw.eq(bo.getFloor() != null, House::getFloor, bo.getFloor());
        lqw.eq(bo.getOrientation() != null, House::getOrientation, bo.getOrientation());
        lqw.eq(StringUtils.isNotBlank(bo.getDescription()), House::getDescription, bo.getDescription());
        return lqw;
    }

    /**
     * 新增【请填写功能名称】
     */
    @Override
    public Boolean insertByBo(HouseBo bo) {
        House add = MapstructUtils.convert(bo, House.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }

        if(CollUtil.isNotEmpty(bo.getAttachments())){
            List<AttachmentBo> attachmentBos = bo.getAttachments();
            List<Attachment> attachments = MapstructUtils.convert(attachmentBos, Attachment.class);
            for (Attachment attachment : attachments) {
                attachment.setSourceType(AttachmentSourceEnum.HOUSE_ATTACH.getCode());
                attachment.setSourceId(add.getId());
            }
            attachmentMapper.insertBatch(attachments);
        }

        if(CollUtil.isNotEmpty(bo.getItems())){
            for (HouseItemBo itemBo : bo.getItems()) {
                HouseItem item = MapstructUtils.convert(itemBo, HouseItem.class);
                item.setHouseId(add.getId());
                houseItemMapper.insert(item);
                if(CollUtil.isNotEmpty(itemBo.getAttachments())){
                    List<AttachmentBo> attachmentBos = itemBo.getAttachments();
                    List<Attachment> attachments = MapstructUtils.convert(attachmentBos, Attachment.class);
                    for (Attachment attachment : attachments) {
                        attachment.setSourceType(AttachmentSourceEnum.ITEM_ATTACH.getCode());
                        attachment.setSourceId(item.getId());
                    }
                    attachmentMapper.insertBatch(attachments);
                }
            }
        }

        return flag;
    }

    @Override
    public Boolean insertByBos(List<HouseBo> bos) {
        if(CollUtil.isEmpty(bos)){
            return false;
        }
        for (HouseBo bo : bos) {
            this.insertByBo(bo);
        }
        return true;
    }

    /**
     * 修改【请填写功能名称】
     */
    @Override
    public Boolean updateByBo(HouseBo bo) {
        House update = MapstructUtils.convert(bo, House.class);
        validEntityBeforeSave(update);

        if(CollUtil.isNotEmpty(bo.getAttachments())){
            List<AttachmentBo> attachmentBos = bo.getAttachments();
            List<Attachment> attachments = MapstructUtils.convert(attachmentBos, Attachment.class);
            for (Attachment attachment : attachments) {
                attachment.setSourceType(AttachmentSourceEnum.HOUSE_ATTACH.getCode());
                attachment.setSourceId(update.getId());
            }
            attachmentMapper.insertOrUpdateBatch(attachments);
        }

        if(CollUtil.isNotEmpty(bo.getItems())){
            for (HouseItemBo itemBo : bo.getItems()) {
                HouseItem item = MapstructUtils.convert(itemBo, HouseItem.class);
                item.setHouseId(update.getId());
                houseItemMapper.insertOrUpdate(item);
                if(CollUtil.isNotEmpty(itemBo.getAttachments())){
                    List<AttachmentBo> attachmentBos = itemBo.getAttachments();
                    List<Attachment> attachments = MapstructUtils.convert(attachmentBos, Attachment.class);
                    for (Attachment attachment : attachments) {
                        attachment.setSourceType(AttachmentSourceEnum.ITEM_ATTACH.getCode());
                        attachment.setSourceId(item.getId());
                    }
                    attachmentMapper.insertOrUpdateBatch(attachments);
                }
            }
        }
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(House entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除【请填写功能名称】
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }
}
